<template>
  <!-- 全局公共导入框 -->
  <el-dialog
    :title="title ? title : $t('导入')"
    :visible.sync="show"
    :before-close="cancel"
    width="400px"
    append-to-body>
    <!-- header -->
    <slot name="header"></slot>
    <el-upload
      ref="upload"
      :limit="1"
      :accept="accept"
      :headers="headers"
      :action="action"
      :on-change="({ raw }) => (formData = raw)"
      :auto-upload="false"
      drag>
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">{{ $t('将文件拖到此处，或点击上传') }}</div>
      <div class="el-upload__tip text-center" slot="tip">
        <el-alert
          v-if="showTip"
          :title="$t('说明:只用于新增')"
          :closable="false"
          type="error"
          style="margin: 5px 0"
          center />
        <slot name="alert"></slot>
        <div>
          <span>{{ tip ? tip : $t('仅允许导入xls、xlsx格式文件。') }}</span>
          <el-link
            v-if="templateUrl"
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="downloadTemplate">
            {{ $t('下载模板') }}
          </el-link>
        </div>
      </div>
    </el-upload>

    <slot></slot>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleSubmit">
        {{ $t('确定') }}
      </el-button>
      <el-button @click="cancel">
        {{ $t('取消') }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getToken } from '@/utils/auth'
import request from '@/utils/request'

export default {
  name: 'Import',
  props: {
    /**
     * title
     */
    title: {
      type: String,
      // default: "导入",
    },
    /**
     * tip 提示
     */
    showTip: {
      type: Boolean,
      default: () => true,
    },
    /**
     * 下载文件名称
     */
    fileName: {
      type: String,
    },
    /**
     * accept
     */
    accept: {
      type: String,
      default: '.xlsx, .xls',
    },
    /**
     * 导入的接口地址
     */
    action: {
      type: String,
      required: true,
    },
    /**
     * 下载模板 接口地址
     */
    templateUrl: {
      type: String,
      default: '',
      // required: true,
    },
    /**
     * 提示信息
     */
    tip: {
      type: String,
      // default: '仅允许导入xls、xlsx格式文件。',
    },
    /**
     * 控制显示隐藏
     */
    show: {
      type: Boolean,
      required: true,
      default: false,
    },
    query: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      // 设置上传的请求头部
      headers: { Authorization: 'Bearer ' + getToken() },
      formData: null,
    }
  },
  watch: {
    show: function (newValue) {
      if (newValue) {
        this.$nextTick(() => {
          this.$refs['upload'].uploadFiles = []
        })
      }
    },
  },
  methods: {
    handleSubmit() {
      if (!this.formData) {
        return this.$message.error(this.$t('请选择'))
      }
      const formData = new FormData()
      console.log(`this.query ==>`, this.query)
      if (JSON.stringify(this.query) != '{}') {
        Object.keys(this.query).forEach((key) => {
          formData.append(key, this.query[key])
        })
      }
      formData.append('file', this.formData)
      request({
        url: this.action,
        data: formData,
        method: 'post',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
          loading: true,
        },
      }).then((res) => {
        const { code, data, msg } = res
        if (code === 200) {
          this.$message({ type: 'success', message: msg })

          this.$emit('success')
          this.cancel()
        }
      })
    },

    downloadTemplate() {
      const fileName = this.fileName ? this.fileName : `template_${new Date().getTime()}`
      this.download(this.templateUrl, {}, fileName + '.xlsx')
    },
    cancel() {
      this.$emit('update:show', false)
    },
  },
}
</script>
<style></style>
